package com.ncmmall.application.business.message;

import com.ncmmall.domain.business.message.Message;
import com.ncmmall.domain.business.message.MessageRepository;
import com.ncmmall.domain.business.message.QMessage;
import com.ncmmall.querychannel.service.QueryChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;

/**
 * 系统消息
 *
 * @author likaikai
 * @date 2019-07-13 14:09
 */
@Service
@Transactional
public class MessageApplication {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private EntityManager em;


    /**
     * 创建消息
     *
     * @param message
     */
    public void create(Message message) {
        message.setCreateTime(new Timestamp(System.currentTimeMillis()));
        if (message.getType() == 1) {
            message.setStatus(1);

            String sql = "update security_web_user set systemMessageNumber = (systemMessageNumber + 1)";
            Query query = em.createNativeQuery(sql);
            query.executeUpdate();
        } else if (message.getType() == 2) {
            message.setSendTime(message.getCreateTime());
            Query query = em.createNativeQuery("update security_web_user set orderMessageNumber = (orderMessageNumber + 1) where id = :id");
            query.setParameter("id", message.getMember().getId());
            query.executeUpdate();
        } else {
            message.setSendTime(message.getCreateTime());
            Query query = em.createNativeQuery("update security_web_user set withDrawMessageNumber = (withDrawMessageNumber + 1) where id = :id");
            query.setParameter("id", message.getMember().getId());
            query.executeUpdate();
        }
        messageRepository.save(message);
    }

    /**
     * 编辑消息
     *
     * @param message
     */
    public void modify(Message params) {

        Message message = queryChannelService.findOne(QMessage.message.id.eq(params.getId()), Message.class);
        message.setTitle(params.getTitle());
        message.setDigest(params.getDigest());
        message.setContent(params.getContent());

        messageRepository.save(message);
    }

    /**
     * 删除消息
     *
     * @param id
     */
    public void remove(Message message) {
        messageRepository.delete(message);
    }


    /**
     * 发送消息
     *
     * @param message
     */
    public void send(Message message) {
        message.setStatus(2);
        message.setSendTime(new Timestamp(System.currentTimeMillis()));
        messageRepository.save(message);
    }

}
